const mysql = require('mysql2');
const pool = mysql.createPool({
    connectionLimit: 37, // 连接池中的最大连接数
    host:"127.0.0.1",
    user:"root",
    password:"root",
    database:"blog",
    port:3306
});

// 断线重连逻辑
const reconnect = (pool) => {
    pool.getConnection((err, connection) => {
      if (err) {
        console.error('Error connecting to the database:', err);
        setTimeout(() => reconnect(pool), 2000); // 2秒后重试连接
      } else {
        console.log('Connected to the database');
        connection.release(); // 释放连接
      }
    });
};
  
// 初始连接
reconnect(pool);

// 监听连接池的事件
pool.on('acquire', (connection) => {
    console.log('Connection %d acquired', connection.threadId);
  
    // 监听连接的查询事件-获取查询sql
    connection.on('query', (query) => {
      console.log('Executing query:', query.sql);
    });
});
//  监听释放连接事件
pool.on('release', (connection) => {
    console.log('Connection %d released', connection.threadId);
});


// 定义查询方法
var query = function(sql, options, callback) {
    pool.query(sql,options,function(err,results,fields){
        if(err){
            console.log("已经断开连接，准备重试...")
            // reconnect(pool) // 断线重连
            callback(err, null, null);
        }else{
            console.log("查询成功")
            callback(err, results, fields);
        }
    })
};

module.exports = query;
